let path = require('path');
let fs = require('fs');
let vm = require('vm');

function Module(id) {
  this.id = id;
  this.exports = {};

}
Module._extensions = {
  '.js'(module){
    let content = fs.readFileSync(module.id,'utf8');
    let fnStr = Module.wrapper[0]+content+Module.wrapper[1]
    let fn = vm.runInThisContext(fnStr);
    fn.call(module.exports,module.exports,module,req)
  },
  '.json'(module){
    let json = fs.readFileSync(module.id,'utf8');
    module.exports = json;

  }
}
Module.wrapper=[
  "(function (exports, module, require, __dirname, __filename) {",

  "})",
]
function tryModuleLoad(module) {
  let extension = path.extname(module.id);
  Module._extensions[extension](module)
}
Module._cache = {};

function req(modulePath) {
  let absPathName = path.resolve(__dirname,modulePath);
  let extNames = Object.keys(Module._extensions);
  let index = -1
  let old = absPathName;

  function find(absPathName) {
    if (index===extNames.length){
      return absPathName;
    }
    try {
      fs.accessSync(absPathName);
      return absPathName;
    }catch (e) {
      let ext = extNames[index++];
      let newPath = old+ext;
      return find(newPath)
    }
  }
  absPathName=find(absPathName);

  try {
    fs.accessSync(absPathName);
  }catch (e) {
    throw new Error('文件不存在');
  }

  if(Module._cache[absPathName]){
    return Module._cache[absPathName].exports;
  }
  let module = new Module(absPathName);
  Module._cache[absPathName] = module;
  tryModuleLoad(module);
  return module.exports;
}


let obj = req('./a');
console.log(obj);
